<?php
/**
 * Created by PhpStorm.
 * 报表类 采用ECharts插件  注意 所有值都要赋初始值 否则会断层
 * User: 李洋波
 * Date: 2016/9/10
 * Time: 9:39
 */

class maintainReport extends My_Controller{
    function __construct()
    {
        parent::__construct();
        //加载模型
        $this->load->model('mt_report_model','reportModel');
    }
    //初始页面
    public function index(){
        $this->StatisticsOrderStatus(date('Y-m-d',time()-24*3600*30),date('Y-m-d',time()));
    }
//------------------------------------------维修质检and处理 报表--------------------------------------
    /**
     * 统计OMS订单状况
     */
    public function StatisticsOrderStatus($startTime='',$endTime=''){
        $gp=gp();
        $startTimeVal=$startTime?$startTime:$gp['startTime'];
        $endTimeVal=$endTime?$endTime:$gp['endTime'];
        //初始化时间轴....
        $timeLine=$this->initializeTimeLine($startTimeVal,$endTimeVal);
        //构建时间轴
        $StatisticsData['timeLine']=$timeLine;
        //构建es接单数据
        $StatisticsData['reception']['es']=$this->StructureStatisticsArray('es','receptionOrderNum',$startTimeVal,$endTimeVal);
        //构建de接单数据
        $StatisticsData['reception']['de']=$this->StructureStatisticsArray('de','receptionOrderNum',$startTimeVal,$endTimeVal);
        //构建es维修单量数据
        $StatisticsData['maintain']['es']=$this->StructureStatisticsArray('es','maintainOrderNum',$startTimeVal,$endTimeVal);
        //构建de维修单量数据
        $StatisticsData['maintain']['de']=$this->StructureStatisticsArray('de','maintainOrderNum',$startTimeVal,$endTimeVal);
        //构建传输数据
        $data['statisticsData']=json_encode($StatisticsData);
        $this->load->view('defaults/report/report_index',$data);
        $this->load->view('defaults/common/footer');
    }

    /**
     * 初始化时间轴
     * @param string $startTime
     * @param string $endTime
     * @return array
     */
    public function initializeTimeLine($startTime='',$endTime=''){
        $timeLine=array();
        if($startTime && $endTime) {
            $minTime=strtotime($startTime);
            $maxTime=strtotime($endTime);
            $intervalDay = floor(($maxTime - $minTime) / (24 * 3600));
        }else{
            //设置最小时间 (OMS第一条数据时间)
            $minTime = strtotime('2015-09-14');
            //设置最大时间
            $maxTime = time();
            //计算间隔天数
            $intervalDay = floor(($maxTime - $minTime) / (24 * 3600))+1;
        }
        //创建时间轴
        for($i=0;$i<=$intervalDay;$i++){
            $timeLine[]=date('Y-m-d',$minTime+($i*24*3600));
        }
        return $timeLine;
    }

    /**
     * 构建统计数组(由于有新旧两套数据，需要分别处理)
     * @param $site
     * @param $type
     * @param string $startTime
     * @param string $endTime
     * @return array
     */
    public function StructureStatisticsArray($site,$type,$startTime='',$endTime=''){
        //初始化数据
        $initData=$this->initializeStatisticsData($startTime,$endTime);
        //统计返回数组
        $StatisticsArray=array();
        //设置基础数据 接单数据or维修单量数据
        $dataOld=array();
        $dataNew=array();
        switch($type){
            case 'receptionOrderNum':
                $dataOld=$this->reportModel->GetOldReceptionOrderNum($site,$startTime,$endTime);
                $dataNew=$this->reportModel->GetNewReceptionOrderNum($site,strtotime($startTime),strtotime($endTime));
                break;
            case 'maintainOrderNum':
                $dataOld=$this->reportModel->GetOldMaintainOrderNum($site,$startTime,$endTime);
                $dataNew=$this->reportModel->GetNewMaintainOrderNum($site,strtotime($startTime),strtotime($endTime));
                break;
            default:
                break;
        }
        //循环数据并构建统计数组(旧)
        if($dataOld) {
            foreach ($dataOld as $oldRow) {
                $oldRow['time']=date('Y-m-d',strtotime($oldRow['time'])+10*3600);
                $initData[trim($oldRow['time'])]+=1;
            }
        }
        //循环数据并构建统计数组(新)
        if($dataNew) {
            foreach ($dataNew as $newRow) {
                $newRow['time']=date('Y-m-d',strtotime($newRow['time'])+10*3600);
                $initData[trim($newRow['time'])]+=1;
            }
        }
        //重构统计数组  转化成 ecchar 能识别的方式
        foreach($initData as $key=>$val){
            $StatisticsArray[]=$val;
        }
        return $StatisticsArray;
    }

    /**
     * 初始化统计数据
     * @param string $startTime
     * @param string $endTime
     * @return array
     */
    public function initializeStatisticsData($startTime='',$endTime=''){
        //初始数据
        $data=array();
        //创建时间轴
        $timeLine=$this->initializeTimeLine($startTime,$endTime);
        if($timeLine) {
            //循环构建初始数据
            foreach ($timeLine as $key => $val) {
                $data[$val] = 0;
            }
        }
        return $data;
    }
//--------------------------------------------------维修状态图表--------------------------------------
    public function statusStatement(){
        $gp=gp();
        //设定默认周期
        $gp['sTime']=$gp['sTime']?:'2016-07-01';
        $gp['nTime']=$gp['nTime']?:date('Y-m-d',time());
        //构建月份轴
        $statusData['time']=array_keys($this->initMonthAxle($gp['sTime'],$gp['nTime']));
        //构建订单状态数据
        $statusData['data']=$this->GetRepairStatusData($gp['merchant_num'],$gp['brandCustomerNum'],$gp['sTime'],$gp['nTime']);
        //平台客户列表
        $data['mCline']=$this->reportModel->GetClineList(1);
        //品牌客户列表
        $data['bCline']=$this->reportModel->GetClineList(2);
        //状态数据
        $data['statusData']=json_encode($statusData);
        $data['statusTime']=$statusData['time'];
        $this->load->view('defaults/report/status_report',$data);
        $this->load->view('defaults/common/footer');
    }

    /**
     * 获取维修状态数据
     * @param string $merchant_num
     * @param string $brandCustomerNum
     * @param string $sTime
     * @param string $nTime
     * @param string $status
     * @return array|bool
     */
    public function GetRepairStatusData($merchant_num='',$brandCustomerNum='',$sTime='',$nTime='',$status=''){
        //获取产品数据
        $data=$this->reportModel->GetProduct($merchant_num,$brandCustomerNum,$sTime,$nTime,$status);
        //初始化月份轴
        $monthAxle=$this->initMonthAxle($sTime,$nTime);
        $waiting = array(1);//待接收
        $repairIng = array(2,3,4,5,6,7,8,9,10,11,12,14,15,16);//维修中
        $repairOk = array(13,17);//维修完成
        foreach($data as $row){
            if(in_array($row['status_id'],$waiting)){
                $monthAxle[date('Y-m',$row['add_time'])]['waitingTotal']++;
                switch($row['point']){
                    case 'es':
                        $monthAxle[date('Y-m',$row['add_time'])]['waiting'][0]++;
                        break;
                    case 'ru':
                        $monthAxle[date('Y-m',$row['add_time'])]['waiting'][1]++;
                        break;
                    case 'de':
                        $monthAxle[date('Y-m',$row['add_time'])]['waiting'][2]++;
                        break;
                    case 'gb':
                        $monthAxle[date('Y-m',$row['add_time'])]['waiting'][3]++;
                        break;
                    case 'us':
                        $monthAxle[date('Y-m',$row['add_time'])]['waiting'][4]++;
                        break;
                    case 'sz':
                        $monthAxle[date('Y-m',$row['add_time'])]['waiting'][5]++;
                        break;
                    default:
                        break;
                }
            }
            if(in_array($row['status_id'],$repairIng)){
                $monthAxle[date('Y-m',$row['add_time'])]['repairIngTotal']++;
                switch($row['point']){
                    case 'es':
                        $monthAxle[date('Y-m',$row['add_time'])]['repairIng'][0]++;
                        break;
                    case 'ru':
                        $monthAxle[date('Y-m',$row['add_time'])]['repairIng'][1]++;
                        break;
                    case 'de':
                        $monthAxle[date('Y-m',$row['add_time'])]['repairIng'][2]++;
                        break;
                    case 'gb':
                        $monthAxle[date('Y-m',$row['add_time'])]['repairIng'][3]++;
                        break;
                    case 'us':
                        $monthAxle[date('Y-m',$row['add_time'])]['repairIng'][4]++;
                        break;
                    case 'sz':
                        $monthAxle[date('Y-m',$row['add_time'])]['repairIng'][5]++;
                        break;
                    default:
                        break;
                }
            }
            if(in_array($row['status_id'],$repairOk)){
                $monthAxle[date('Y-m',$row['add_time'])]['repairOkTotal']++;
                switch($row['point']){
                    case 'es':
                        $monthAxle[date('Y-m',$row['add_time'])]['repairOk'][0]++;
                        break;
                    case 'ru':
                        $monthAxle[date('Y-m',$row['add_time'])]['repairOk'][1]++;
                        break;
                    case 'de':
                        $monthAxle[date('Y-m',$row['add_time'])]['repairOk'][2]++;
                        break;
                    case 'gb':
                        $monthAxle[date('Y-m',$row['add_time'])]['repairOk'][3]++;
                        break;
                    case 'us':
                        $monthAxle[date('Y-m',$row['add_time'])]['repairOk'][4]++;
                        break;
                    case 'sz':
                        $monthAxle[date('Y-m',$row['add_time'])]['repairOk'][5]++;
                        break;
                    default:
                        break;
                }
            }
            switch($row['point']){
                case 'es':
                    $monthAxle[date('Y-m',$row['add_time'])]['total'][0]++;
                    break;
                case 'ru':
                    $monthAxle[date('Y-m',$row['add_time'])]['total'][1]++;
                    break;
                case 'de':
                    $monthAxle[date('Y-m',$row['add_time'])]['total'][2]++;
                    break;
                case 'gb':
                    $monthAxle[date('Y-m',$row['add_time'])]['total'][3]++;
                    break;
                case 'us':
                    $monthAxle[date('Y-m',$row['add_time'])]['total'][4]++;
                    break;
                case 'sz':
                    $monthAxle[date('Y-m',$row['add_time'])]['total'][5]++;
                    break;
                default:
                    break;
            }
        }
        return $monthAxle;
    }

    /**
     * 初始化月份轴
     * @param $s
     * @param $n
     * @return array|bool
     */
    public function initMonthAxle($s,$n){
        $data = array();
        $dateS=explode('-',$s);
        $dataN=explode('-',$n);
        $yearS=(int)$dateS[0];//初始年份
        $monthS=(int)$dateS[1];//初始月份
        $yearN=(int)$dataN[0];//结束年份
        $monthN=(int)$dataN[1];//结束月份
        $values=array(
            'total'=>array(0,0,0,0,0,0),
            'waiting'=>array(0,0,0,0,0,0),
            'repairIng'=>array(0,0,0,0,0,0),
            'repairOk'=>array(0,0,0,0,0,0),
            'waitingTotal'=>0,
            'repairIngTotal'=>0,
            'repairOkTotal'=>0,
        );
        if(strtotime($s) >= strtotime($n)){
            return false;
        }else {
            $yearInterval = $yearN - $yearS;//年份间隔
            $monthInterval = $monthN + (12 * $yearInterval);//月份横向间隔（忽略前置）
            //构建月份轴数据
            for ($i = $monthS; $i <= $monthInterval; $i++) {
                if($i > 12){
                    $j = floor($i/12);
                    if($i%12===0){
                        $j-=1;
                    }
                    $data[($yearS+$j) . '-' . str_pad(($i-($j*12)),2,'0',STR_PAD_LEFT)] = $values;
                }else {
                    $data[$yearS . '-' . str_pad($i,2,'0',STR_PAD_LEFT)] = $values;
                }
            }
            return $data;
        }
    }
    //--------------------------------------------------维修点KPI------------------------------------------------
    /**
     * 维修平均时长
     */
    public function repairComprehensiveKpi(){
        $gp=gp();
        $point=$gp['point']?$gp['point']:'es';
        $sTime=$gp['sTime']?$gp['sTime']:date('Y-m-01',time());//默认时间
        $nTime=$gp['nTime']?$gp['nTime']:date('Y-m-01',strtotime('+1 month'));//默认时间
        $type=$gp['type']?$gp['type']:'time';//数据类型（平均时长|处理单量）
        $timeLine=$gp['timeLine']?:1;
        $repairData=$this->getRepairComprehensiveData($point,strtotime($sTime),strtotime($nTime));
        //判断是否使用自定义区间
        if($timeLine && $timeLine !=1) {
            //将数组进行自定义区间离散
            $dataTime=$this->getTimeInterval($repairData[$type],$timeLine,1);
            //获取时间轴
            $eCharts['time'] = array_keys($dataTime);
            //维修综合数据
            $eCharts['data'] = $dataTime;
        }else{
            //获取时间轴
            $eCharts['time'] = array_keys($repairData[$type]);
            //维修综合数据
            $eCharts['data'] = $repairData[$type];
        }
        $data['eCharts']=json_encode($eCharts);
        $data['time']=$eCharts['time'];
        //关键字
        $keyword['point']=$point;
        $keyword['sTime']=$sTime;
        $keyword['nTime']=$nTime;
        $keyword['type']=$type;
        $keyword['timeLine']=$timeLine;
        switch($type){
            case 'time':
                $typeName='平均时长';
                break;
            case 'num':
                $typeName='处理单量';
                break;
            default:
                $typeName='平均时长';
                break;
        }
        $keyword['typeName']=$typeName;
        $data['keyword']=$keyword;
        //站点列表
        $pointList=$this->reportModel->GetPointList();
        $data['pointList']=$pointList;
        $this->load->view('defaults/report/repair_kpi',$data);
        $this->load->view('defaults/common/footer');
    }

    /**
     * 维修数量
     */
    public function repairComprehensiveKpiNum(){
        $gp=gp();
        $point=$gp['point']?$gp['point']:'es';
        $sTime=$gp['sTime']?$gp['sTime']:date('Y-m-01',time());//默认时间
        $nTime=$gp['nTime']?$gp['nTime']:date('Y-m-01',strtotime('+1 month'));//默认时间
        $timeLine=$gp['timeLine']?:1;
        $rData=$this->StructureProductTrack($point,strtotime($sTime),strtotime($nTime));
        $numData=$rData['num'];
        foreach($numData as &$row){
            $row['unpack_detection']=$row['unpack_detection']?$row['unpack_detection']:0;
            $row['their_repair']=$row['their_repair']?$row['their_repair']:0;
            $row['quote']=$row['quote']?$row['quote']:0;
            $row['quote_ok']=$row['quote_ok']?$row['quote_ok']:0;
            $row['repair_ing']=$row['repair_ing']?$row['repair_ing']:0;
            $row['repair_ok']=$row['repair_ok']?$row['repair_ok']:0;
            $row['output_detection']=$row['output_detection']?$row['output_detection']:0;
            $row['shipped_ok']=$row['shipped_ok']?$row['shipped_ok']:0;
            $row['received']=$row['received']?$row['received']:0;
            $row['parts_ing']=$row['parts_ing']?$row['parts_ing']:0;
        }
        unset($row);
        //判断是否使用自定义区间
        if($timeLine && $timeLine !=1) {
            //将数组进行自定义区间离散
            $dataTime=$this->getTimeInterval($numData,$timeLine,2);
            //获取时间轴
            $eCharts['time'] = array_keys($dataTime);
            //维修综合数据
            $eCharts['data'] = $dataTime;
        }else{
            $eCharts['data']=$numData;
            $eCharts['time']=array_keys($rData['num']);
        }
        //关键字
        $keyword['point']=$point;
        $keyword['sTime']=$sTime;
        $keyword['nTime']=$nTime;
        $keyword['timeLine']=$timeLine;
        $data['keyword']=$keyword;
        //站点列表
        $pointList=$this->reportModel->GetPointList();
        $data['pointList']=$pointList;
        //数据
        $data['eCharts']=json_encode($eCharts);
        $data['time']=$eCharts['time'];
        $this->load->view('defaults/report/kpi_num',$data);
        $this->load->view('defaults/common/footer');
    }

    /**
     * 获取维修点
     * @param $point
     * @param $sTime
     * @param $nTime
     * @return array
     */
    public function getRepairComprehensiveData($point,$sTime,$nTime){
        $workdayData=$this->getTrackWorkday($point,$sTime,$nTime);
        $data=array();
        //数据统计
        foreach($workdayData as $key=>$val){
            foreach($val as $keyMin=>$valMin){
                if($valMin['detectionStart_workday']){
                    $data[$key]['detectionStart_num']++;
                    $data[$key]['detectionStart_workday']+=$valMin['detectionStart_workday'];
                }
                if($valMin['repairStart_workday']){
                    $data[$key]['repairStart_num']++;
                    $data[$key]['repairStart_workday']+=$valMin['repairStart_workday'];
                }
                if($valMin['quote_workday']){
                    $data[$key]['quote_num']++;
                    $data[$key]['quote_workday']+=$valMin['quote_workday'];
                }
                if($valMin['quote_ok_workday']){
                    $data[$key]['quote_ok_num']++;
                    $data[$key]['quote_ok_workday']+=$valMin['quote_ok_workday'];
                }
                if($valMin['quote_repair_workday']){
                    $data[$key]['quote_repair_num']++;
                    $data[$key]['quote_repair_workday']+=$valMin['quote_repair_workday'];
                }
                if($valMin['repairOK_workday']){
                    $data[$key]['repairOK_num']++;
                    $data[$key]['repairOK_workday']+=$valMin['repairOK_workday'];
                }
                if($valMin['qc_ok_workday']){
                    $data[$key]['qc_ok_num']++;
                    $data[$key]['qc_ok_workday']+=$valMin['qc_ok_workday'];
                }
                if($valMin['shippedOk_workday']){
                    $data[$key]['shippedOk_num']++;
                    $data[$key]['shippedOk_workday']+=$valMin['shippedOk_workday'];
                }
                if($valMin['quote_parts_workday']){
                    $data[$key]['parts_ing_num']++;
                    $data[$key]['quote_parts_workday']+=$valMin['quote_parts_workday'];
                }
            }
        }
        $timeData=array();//平均时长数据
        $numData=array();//处理单量数据
        //构建数据
        foreach($data as $dKey=>$dVal){
            $detectionStart_workday=0;
            $repairStart_workday=0;
            $quote_workday=0;
            $quote_ok_workday=0;
            $quote_repair_workday=0;
            $repairOK_workday=0;
            $qc_ok_workday=0;
            $shippedOk_workday=0;
            $quote_parts_workday=0;
            if($dVal['detectionStart_num']){
                $detectionStart_workday=$dVal['detectionStart_workday']/$dVal['detectionStart_num'];
            }else{
                $dVal['detectionStart_num']=0;
            }
            if($dVal['repairStart_num']){
                $repairStart_workday=$dVal['repairStart_workday']/$dVal['repairStart_num'];
            }else{
                $dVal['repairStart_num']=0;
            }
            if($dVal['quote_num']){
                $quote_workday=$dVal['quote_workday']/$dVal['quote_num'];
            }else{
                $dVal['quote_num']=0;
            }
            if($dVal['quote_ok_num']){
                $quote_ok_workday=$dVal['quote_ok_workday']/$dVal['quote_ok_num'];
            }else{
                $dVal['quote_ok_num']=0;
            }
            if($dVal['quote_repair_num']){
                $quote_repair_workday=$dVal['quote_repair_workday']/$dVal['quote_repair_num'];
            }else{
                $dVal['quote_repair_num']=0;
            }
            if($dVal['repairOK_num']){
                $repairOK_workday=$dVal['repairOK_workday']/$dVal['repairOK_num'];
            }else{
                $dVal['repairOK_num']=0;
            }
            if($dVal['qc_ok_num']){
                $qc_ok_workday=$dVal['qc_ok_workday']/$dVal['qc_ok_num'];
            }else{
                $dVal['qc_ok_num']=0;
            }
            if($dVal['shippedOk_num']){
                $shippedOk_workday=$dVal['shippedOk_workday']/$dVal['shippedOk_num'];
            }else{
                $dVal['shippedOk_num']=0;
            }
            if($dVal['parts_ing_num']){
                $quote_parts_workday=$dVal['quote_parts_workday']/$dVal['parts_ing_num'];
            }else{
                $dVal['parts_ing_num']=0;
            }
            $timeData[$dKey]=array(
                round($detectionStart_workday,1),
                round($repairStart_workday,1),
                round($quote_workday,1),
                round($quote_ok_workday,1),
                round($quote_repair_workday,1),
                round($repairOK_workday,1),
                round($qc_ok_workday,1),
                round($shippedOk_workday,1),
                round($quote_parts_workday,1)
            );
            $numData[$dKey]=array(
                $dVal['detectionStart_num'],
                $dVal['repairStart_num'],
                $dVal['quote_num'],
                $dVal['quote_ok_num'],
                $dVal['quote_repair_num'],
                $dVal['repairOK_num'],
                $dVal['qc_ok_num'],
                $dVal['shippedOk_num'],
                $dVal['parts_ing_num']
            );
        }
        $rData['time']=$timeData;
        $rData['num']=$numData;
        return $rData;
    }
    /**
     * 获取轨迹工作日
     * @param $point
     * @param $sTime
     * @param $nTime
     * @return array
     */
    public function getTrackWorkday($point,$sTime,$nTime){
        $rData=$this->StructureProductTrack($point,$sTime,$nTime);
        $trackData=$rData['time'];
        $data=array();
        //进行轨迹各阶段工作日计算
        foreach($trackData as $key=>$val){
            foreach($val as $keyMin=>$valMin){
                $data[$key][$keyMin]=array(//初始化数据
                    'detectionStart_workday'=>0,
                    'repairStart_workday'=>0,
                    'quote_workday'=>0,
                    'quote_ok_workday'=>0,
                    'quote_repair_workday'=>0,
                    'repairOK_workday'=>0,
                    'qc_ok_workday'=>0,
                    'shippedOk_workday'=>0,
                    'quote_parts_workday'=>0
                );
                //已到货-->检测完成待维修
                if($valMin['test_repair_time']){
                    $received_time=$this->reportModel->getTrackTime($keyMin,18);
                    $data[$key][$keyMin]['detectionStart_workday']=$this->getWorkday($valMin['test_repair_time'],$received_time);
                }
                //检测完成待维修-->接单维修
                if($valMin['their_repair_time']){
                    $test_repair_time=$this->reportModel->getTrackTime($keyMin,2);
                    $data[$key][$keyMin]['repairStart_workday']=$this->getWorkday($valMin['their_repair_time'],$test_repair_time);
                }
                //接单维修-->已报价
                if($valMin['quote_time']){
                    $their_repair_time=$this->reportModel->getTrackTime($keyMin,3);
                    $data[$key][$keyMin]['quote_workday']=$this->getWorkday($valMin['quote_time'],$their_repair_time);
                }
                //已报价-->同意/拒绝报价
                if($valMin['quote_ok_time']){
                    $quote_time=$this->reportModel->getTrackTime($keyMin,5);
                    $data[$key][$keyMin]['quote_ok_workday']=$this->getWorkday($valMin['quote_ok_time'],$quote_time);
                }
                //同意/拒绝报价-->维修中
                if($valMin['repair_ing_time']){
                    $quote_ok_time=$this->reportModel->getTrackTime($keyMin,6);
                    $quote_no_time=$this->reportModel->getTrackTime($keyMin,7);
                    $qr_time=$quote_ok_time?$quote_ok_time:$quote_no_time;
                    $data[$key][$keyMin]['quote_repair_workday']=$this->getWorkday($valMin['repair_ing_time'],$qr_time);
                }
                //同意/拒绝报价-->维修中_等待配件
                if($valMin['await_parts_time']){
                    $quote_ok_time=$this->reportModel->getTrackTime($keyMin,6);
                    $quote_no_time=$this->reportModel->getTrackTime($keyMin,7);
                    $qr_time=$quote_ok_time?$quote_ok_time:$quote_no_time;
                    $data[$key][$keyMin]['quote_parts_workday']=$this->getWorkday($valMin['repair_ing_time'],$qr_time);
                }
                //维修中-->维修完成待QC
                if($valMin['repair_ok_time']){
                    //判断是否多次维修
                    $num=$this->reportModel->getTrackNum($keyMin,9);
                    if($num > 1){
                        $repair_ing_time = $this->reportModel->getTrackTime($keyMin, 6);
                    }else {
                        $repair_ing_time = $this->reportModel->getTrackTime($keyMin, 9);
                    }
                    $data[$key][$keyMin]['repairOK_workday']=$this->getWorkday($valMin['repair_ok_time'],$repair_ing_time);
                }
                //维修完成待QC-->QC完成
                if($valMin['qc_ok_time']){
                    $repair_ok_time=$this->reportModel->getTrackTime($keyMin,10);
                    $data[$key][$keyMin]['qc_ok_workday']=$this->getWorkday($valMin['qc_ok_time'],$repair_ok_time);
                }
                //QC完成-->已发货(已入库)
                if($valMin['shipped_ok_time']){
                    $qc_okr_time=$this->reportModel->getTrackTime($keyMin,12);
                    $qc_okf_time=$this->reportModel->getTrackTime($keyMin,14);
                    $qc_ok_time=$qc_okf_time?$qc_okf_time:$qc_okr_time;
                    $data[$key][$keyMin]['shippedOk_workday']=$this->getWorkday($valMin['shipped_ok_time'],$qc_ok_time);
                }
            }
        }
        return $data;
    }

    /**
     * 重构维修轨迹
     * @param $point
     * @param $sTime
     * @param $nTime
     * @return array
     */
    public function StructureProductTrack($point,$sTime,$nTime){
        //产品轨迹数据
        $trackData=$this->reportModel->GetProductTrackRepair($point,$sTime,$nTime);
        //轨迹时间数据
        $data=array();
        //轨迹量数据
        $numData=array();
        //统计数据
        $pidData=array();
        //构建维修轨迹时间数据
        foreach($trackData as $row){
            switch($row['end_sid']){
                case '2':
                    //检测完成待维修
                    $numData[date('Y-m-d',$row['add_time'])]['unpack_detection']++;
                    $data[date('Y-m-d',$row['add_time'])][$row['pid']]['test_repair_time']=date('Y-m-d H:i:s',$row['add_time']);
                    break;
                case '15':
                    //检测完成待QC
                    $numData[date('Y-m-d',$row['add_time'])]['unpack_detection']++;
                    $data[date('Y-m-d',$row['add_time'])][$row['pid']]['test_repair_time']=date('Y-m-d H:i:s',$row['add_time']);
                    break;
                case '3':
                    //接单(维修)
                    $numData[date('Y-m-d',$row['add_time'])]['their_repair']++;
                    $data[date('Y-m-d',$row['add_time'])][$row['pid']]['their_repair_time']=date('Y-m-d H:i:s',$row['add_time']);
                    break;
                case '4':
                    //待报价
                    $numData[date('Y-m-d',$row['add_time'])]['quote']++;
                    $data[date('Y-m-d',$row['add_time'])][$row['pid']]['quote_time']=date('Y-m-d H:i:s',$row['add_time']);
                    break;
                case '5':
                    //已报价
                    $numData[date('Y-m-d',$row['add_time'])]['quote']++;
                    $data[date('Y-m-d',$row['add_time'])][$row['pid']]['quote_time']=date('Y-m-d H:i:s',$row['add_time']);
                    break;
                case '6':
                    //同意报价
                    $numData[date('Y-m-d',$row['add_time'])]['quote_ok']++;
                    $data[date('Y-m-d',$row['add_time'])][$row['pid']]['quote_ok_time']=date('Y-m-d H:i:s',$row['add_time']);
                    break;
                case '7':
                    //拒绝报价
                    $numData[date('Y-m-d',$row['add_time'])]['quote_ok']++;
                    $data[date('Y-m-d',$row['add_time'])][$row['pid']]['quote_ok_time']=date('Y-m-d H:i:s',$row['add_time']);
                    break;
                case '8':
                    //维修中_等待配件
                    $pidData[$row['pid']][8]=1;
                    if($pidData[$row['pid']][9] != 1) {
                        $numData[date('Y-m-d', $row['add_time'])]['parts_ing']++;
                    }
                    $data[date('Y-m-d',$row['add_time'])][$row['pid']]['await_parts_time']=date('Y-m-d H:i:s',$row['add_time']);
                    break;
                case '9':
                    //维修中
                    $pidData[$row['pid']][9]=1;
                    if($pidData[$row['pid']][8] != 1) {
                        $numData[date('Y-m-d', $row['add_time'])]['repair_ing']++;
                    }
                    $data[date('Y-m-d',$row['add_time'])][$row['pid']]['repair_ing_time']=date('Y-m-d H:i:s',$row['add_time']);
                    break;
                case '10':
                    /*//维修完成(移除检测失败，需要从新维修的情况)
                    if($maxSid >= 10) {*/
                    $numData[date('Y-m-d',$row['add_time'])]['repair_ok']++;
                    $data[date('Y-m-d',$row['add_time'])][$row['pid']]['repair_ok_time'] = date('Y-m-d H:i:s', $row['add_time']);
                    //}
                    break;
                case '12':
                    //qc完成（入库）
                    $numData[date('Y-m-d',$row['add_time'])]['output_detection']++;
                    $data[date('Y-m-d',$row['add_time'])][$row['pid']]['qc_ok_time']=date('Y-m-d H:i:s',$row['add_time']);
                    break;
                case '14':
                    //qc完成（发货）
                    $numData[date('Y-m-d',$row['add_time'])]['output_detection']++;
                    $data[date('Y-m-d',$row['add_time'])][$row['pid']]['qc_ok_time']=date('Y-m-d H:i:s',$row['add_time']);
                    break;
                case '13':
                    //已入库
                    $numData[date('Y-m-d',$row['add_time'])]['shipped_ok']++;
                    $data[date('Y-m-d',$row['add_time'])][$row['pid']]['shipped_ok_time']=date('Y-m-d H:i:s',$row['add_time']);
                    break;
                case '16':
                    //装配完成
                    $numData[date('Y-m-d',$row['add_time'])]['repair_ok']++;
                    $data[date('Y-m-d',$row['add_time'])][$row['pid']]['repair_ok_time'] = date('Y-m-d H:i:s', $row['add_time']);
                    break;
                case '17':
                    //已发货
                    $numData[date('Y-m-d',$row['add_time'])]['shipped_ok']++;
                    $data[date('Y-m-d',$row['add_time'])][$row['pid']]['shipped_ok_time']=date('Y-m-d H:i:s',$row['add_time']);
                    break;
                case '18':
                    //已收货
                    $numData[date('Y-m-d',$row['add_time'])]['received']++;
                    $data[date('Y-m-d',$row['add_time'])][$row['pid']]['received_time']=date('Y-m-d H:i:s',$row['add_time']);
                    break;
                default :
                    break;
            }
        }
        $rData['time']=$data;
        $rData['num']=$numData;
        return $rData;
    }
//------------------------------------------------------数据导出---------------------------------------
    /**
     * 导出数据列表
     */
    public function ExportDataList(){
        $gp=gp();
        //获取产品状态
        $productStatus=$this->reportModel->GetProductStatus();
        //获取订单状态
        $orderStatus=$this->reportModel->GetOrderStatus();
        //平台客户列表
        $platformClineList=$this->reportModel->GetClineList(1);
        //品牌客户列表
        $brandClineList=$this->reportModel->GetClineList(2);
        //站点列表
        $pointList=$this->reportModel->GetPointList();
        //维修师列表
        $role[5]=$this->reportModel->getRepairPeopleList(5);
        //出库质检员列表
        $role[6]=$this->reportModel->getRepairPeopleList(6);
        //拆包质检员列表
        $role[4]=$this->reportModel->getRepairPeopleList(4);
        //发货员列表
        $role[9]=$this->reportModel->getRepairPeopleList(9);
        //收货员列表
        $role[3]=$this->reportModel->getRepairPeopleList(3);
        //构建前端数据
        $data['productStatus']=$productStatus;
        $data['orderStatus']=$orderStatus;
        $data['platformClineList']=$platformClineList;
        $data['brandClineList']=$brandClineList;
        $data['pointList']=$pointList;
        $data['role']=$role;
        $data['data']=$gp['data'];
        $this->load->view('defaults/report/export_data',$data);
        $this->load->view('defaults/common/footer');
    }

    /**
     * 数据上传
     */
    public function dataUploadList(){
        $gp=gp();
        //查询条件
        $gp['page']=$gp['page']?:1;
        $str="?client_id=".$gp['client_id'].'&title='.$gp['title'];
        //平台客户列表
        $platformClineList=$this->reportModel->GetClineList(1);
        //分页查询
        $this->load->library('pagination');
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url('maintainReport/maintainReport/dataUploadList'.$str);
        $config['per_page'] = 15;
        $repairFile=$this->reportModel->getFileList($gp['client_id'],trim($gp['title']),$config['per_page'],($gp['page']-1)*$config['per_page']);
        $config['total_rows'] = count($repairFile);
        $config['uri_segment'] = config_item('enable_lang')?5:4;
        $this->pagination->initialize($config);
        $data['pageShow']= $this->pagination->create_links();
        //分页结束
        $data['repairFile']=$repairFile;
        $data['platformClineList']=$platformClineList;
        $this->load->view('defaults/report/upload_data',$data);
        $this->load->view('defaults/common/footer');
    }

    /**
     * 上传文件
     */
    public function uploadFile(){
        $gp=gp();
        $uploaddir = './resource/uploadfiles/file/uploadify/';
        $fileretrun = uploadfile($_FILES['filename'],$uploaddir);
        $data=array(
            'filename'=>$fileretrun,
            'typeid'=>9,
            'typename'=>'维修数据',
            'title'=>$gp['title'],
            'add_time'=>time(),
            'user_id'=>$this->users['id'],
            'client_id'=>$gp['client_id']
        );
        $result=$this->common_model->insert('files_mg',$data);
        if($result){
            if(ENVIRONMENT == 'development'){
                $url = 'http://test.dhhtgroup.com:8099/api/index.php/addRepairDownload';
            }else{
                $url = 'http://www.tomrepair.cn/api/index.php/addRepairDownload';
            }
            $data_to_post['user'] = 'api@tomrepair.es';
            $data_to_post['token'] = '78de933bd0fbacf02ef2de1116e3338f1c627b07';
            $data_to_post['repair']=array('user_id'=>$gp['client_id'],'download_url'=>$fileretrun,'status'=>'1','title'=>$gp['title']);
            $return=TomRepairCurlPost($url,$data_to_post);
        }
        redirect(blang_url('maintainReport/maintainReport/dataUploadList'));
    }

    /**
     * 获取双休日量
     * @param string $day_max
     * @param string $day_min
     * @return int
     */
    public function GetWeekendDay($day_max='',$day_min=''){
        $s=0;
        $day_max=explode(' ',$day_max);
        $day_max=strtotime($day_max[0]);
        $day_min=explode(' ',$day_min);
        $day_min=strtotime($day_min[0]);
        if($day_max && $day_min) {
            $day_time = 3600 * 24;
            $day_diff = ceil(($day_max - $day_min) / $day_time);
            for ($i = 0; $i <= $day_diff; $i++) {
                $day_w = date('w', $day_min + $i * $day_time);
                if ($day_w == 0 || $day_w == 6) {
                    $s++;
                }
            }
        }
        return $s;
    }

    /**
     * 获取工作日量
     * @param string $maxTime
     * @param string $minTime
     * @return float|int
     */
    public function getWorkday($maxTime='',$minTime=''){
        $day=0;
        if($maxTime!='' && $minTime!=''){
            $weekendDay=$this->GetWeekendDay($maxTime,$minTime);
            $day=round((strtotime($maxTime) - strtotime($minTime)) / (3600 * 24),1)-$weekendDay;
            if($day < 0){
                $day=0;
            }
        }
        return $day;
    }

    /**
     * 获取时间区间
     * @param $data
     * @param $timeLine
     * @param $type
     * @return array
     */
    public function getTimeInterval($data,$timeLine,$type){
        //将KPI数据离散为"区间"
        $dataArray = array_chunk($data, $timeLine, true);
        //区间字符集
        $str = '第';//描述符
        $intervalStr = array(7 => '周', 15 => '半月', 30 => '月', 90 => '季度');
        //重构日期KPI数组
        $dataTime = array();
        foreach ($dataArray as $key => $val) {
            foreach ($val as $keyM => $valM) {
                //调整不同的数据结构
                switch($type){
                    case '1':
                        $dataTime[$str . ($key + 1) . $intervalStr[$timeLine]][0] += $valM[0];
                        $dataTime[$str . ($key + 1) . $intervalStr[$timeLine]][1] += $valM[1];
                        $dataTime[$str . ($key + 1) . $intervalStr[$timeLine]][2] += $valM[2];
                        $dataTime[$str . ($key + 1) . $intervalStr[$timeLine]][3] += $valM[3];
                        $dataTime[$str . ($key + 1) . $intervalStr[$timeLine]][4] += $valM[4];
                        $dataTime[$str . ($key + 1) . $intervalStr[$timeLine]][5] += $valM[5];
                        $dataTime[$str . ($key + 1) . $intervalStr[$timeLine]][6] += $valM[6];
                        $dataTime[$str . ($key + 1) . $intervalStr[$timeLine]][7] += $valM[7];
                        $dataTime[$str . ($key + 1) . $intervalStr[$timeLine]][8] += $valM[8];
                        break;
                    case '2':
                        $dataTime[$str . ($key + 1) . $intervalStr[$timeLine]]['unpack_detection'] += $valM['unpack_detection'];
                        $dataTime[$str . ($key + 1) . $intervalStr[$timeLine]]['their_repair'] += $valM['their_repair'];
                        $dataTime[$str . ($key + 1) . $intervalStr[$timeLine]]['quote'] += $valM['quote'];
                        $dataTime[$str . ($key + 1) . $intervalStr[$timeLine]]['quote_ok'] += $valM['quote_ok'];
                        $dataTime[$str . ($key + 1) . $intervalStr[$timeLine]]['repair_ing'] += $valM['repair_ing'];
                        $dataTime[$str . ($key + 1) . $intervalStr[$timeLine]]['repair_ok'] += $valM['repair_ok'];
                        $dataTime[$str . ($key + 1) . $intervalStr[$timeLine]]['output_detection'] += $valM['output_detection'];
                        $dataTime[$str . ($key + 1) . $intervalStr[$timeLine]]['shipped_ok'] += $valM['shipped_ok'];
                        $dataTime[$str . ($key + 1) . $intervalStr[$timeLine]]['received'] += $valM['received'];
                        $dataTime[$str . ($key + 1) . $intervalStr[$timeLine]]['parts_ing'] += $valM['parts_ing'];
                        break;
                    default:
                        break;
                }
            }
        }
        return $dataTime;
    }
}